<template>
  <basic-container>
    <div class="receiving-container">
      <el-row>
        <!--左侧表单-->
        <el-col :span="8">
          <div class="avue-group__header avue-group">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h1 class="avue-group__title">物料合并</h1>
          </div>
          <avue-form ref="properties" v-model="properties" :option="propertiesOption" @submit="handleMovementSubmit">
            <template slot="sequenceNumber">
              <el-input
                v-model="properties.sequenceNumber"
                name="sequenceNumber"
                :clearable="true"
                placeholder="请选择内包条码"
                suffix-icon="iconfont iconicon_scan"
                @keydown.enter.native="enterSequenceNumber(properties.sequenceNumber)"
              ></el-input>
            </template>
          </avue-form>
        </el-col>
        <!--右侧表格-->
        <el-col :span="16">
          <div class="avue-group__header avue-group">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h1 class="avue-group__title">已扫描条码列表</h1>
          </div>
          <avue-crud
            :option="option"
            :table-loading="loading"
            :data="data"
            :page.sync="page"
            :permission="permissionList"
            @search-change="searchChange"
            @search-reset="searchReset"
            @row-del="rowDel"
            @row-update="addUpdate"
            @row-save="rowSave"
          >
          </avue-crud>
        </el-col>
      </el-row>
    </div>
    <!-- 通用模态框-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { check, packMerge } from '@/api/warehouse/materialMerge';
import { mapGetters } from 'vuex';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
export default {
  components: {
    commonModalTemplate
  },
  name: 'otherReceiveMaterial',
  data() {
    return {
      modalName: '',
      receivingType: 'handMovement',
      timer: new Date().getTime(),
      properties: {},
      tableOption: {},
      propertiesOption: {
        submitText: '合并',
        labelWidth: 130,
        menuSpan: 20,
        column: [
          {
            label: '内包条码',
            prop: 'sequenceNumber',
            row: true,
            span: 20,
            rules: [
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (this.data.length === 0) {
                    callback(new Error('请扫描内包条码'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '产品编码',
            prop: 'partMasterCode',
            disabled: true,
            span: 20,
            row: true
          },
          {
            label: '产品名称',
            prop: 'partMasterName',
            disabled: true,
            span: 20,
            row: true
          },
          {
            label: '条码规则',
            prop: 'sequenceDefinitionName',
            type: 'search',
            span: 20,
            row: true,
            disabled: true,
            appendClick: () => {
              this.openSequenceDefinitionModal();
            },
            rules: [
              {
                required: true,
                message: '请选择条码规则',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '标签模板',
            prop: 'labelTemplateName',
            type: 'search',
            span: 20,
            row: true,
            disabled: true,
            appendClick: () => {
              this.openLabelTemplateModal();
            },
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '打印机',
            prop: 'printerName',
            type: 'search',
            span: 20,
            row: true,
            disabled: true,
            appendClick: () => {
              this.openPrintersModal();
            },
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: [],
      localData: [], // 存储数据 用于搜索
      query: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      loading: false,
      option: {
        height: 'calc(100vh - 600px)',
        calcHeight: 30,
        rowKey: 'partNo',
        tip: false,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        selection: false,
        dialogClickModal: false,
        searchLabelWidth: 100,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        refreshBtn: false,
        searchShowBtn: false,
        delBtn: true,
        menuWidth: 200,
        menu: true,
        columnBtn: false,
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '包装数量',
            prop: 'quantity'
          }
        ]
      },
      customAttributeList: [] //扩展属性
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    }
  },
  created() {
    let path = this.$route.path;
    getAttributeConfigList(path).then((res) => {
      this.customAttributeList = this._get(res, 'data.data', []);
      this._forEach(this.customAttributeList, (item) => {
        this.propertiesOption.column.push({
          label: item.lableCnName,
          prop: item.attributeKey,
          type: item.controlType,
          value: item.defaultValue,
          dispaly: item.enabled,
          span: 20
        });
      });
    });
  },
  methods: {
    enterSequenceNumber(sequenceNumber) {
      if (!sequenceNumber) {
        this.$message({
          type: 'warning',
          message: '包装条码不能为空!'
        });
        return;
      }
      let params = {
        transactionType: 'MERGE',
        packSeqNumList: [sequenceNumber]
      };
      check(params).then((res) => {
        let data = res.data.data;
        let sequenceNumberInfo = data[0];
        let flag = this.data.some((item) => {
          return sequenceNumberInfo.sequenceNumber === item.sequenceNumber;
        });
        if (flag) {
          this.$message({
            type: 'warning',
            message: '该包装已经扫描，请勿重复扫描!'
          });
          return;
        }
        if (sequenceNumberInfo.partMasterCode === this.properties.partMasterCode || !this.properties.partMasterCode) {
          this.properties = this._cloneDeep({
            ...sequenceNumberInfo,
            sequenceDefinitionId: sequenceNumberInfo.sequenceDefinitionIdCategory
          });
          this.data.push(sequenceNumberInfo);
          this.properties.sequenceNumber = '';
        } else {
          this.$message({
            type: 'warning',
            message: '产品编码不一致，不可合并!'
          });
        }
      });
      console.log(sequenceNumber, 'enterSequenceNumber');
    },
    async handleMovementSubmit(form, done) {
      if (this.data.length == 0) {
        this.$message({
          type: 'warning',
          message: '请扫描包装条码!'
        });
        return;
      }
      const tempData = this._cloneDeep(this.properties);
      let params = {
        transactionType: 'MERGE',
        packingList: this.data,
        // extFields: this.extFields,
        equipmentId: tempData.printerId,
        sequenceDefinitionId: tempData.sequenceDefinitionId,
        labelTemplateId: tempData.labelTemplateId
      };
      packMerge(params).then((res) => {
        this.$refs.properties.resetFields();
        this.properties = {};
        this.data = [];
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      });
      done();
    },
    rowDel(row, index) {
      this.$confirm('此操作将删除该包装条码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.data.splice(index, 1);
      });
    },
    addUpdate(form, index, done, loading) {
      done();
    },
    rowSave(form, done) {
      done();
    },
    getSelectedRows(rowData, title) {
      switch (this.modalName) {
        case 'sequenceDefineModal':
          this.properties.sequenceDefinitionName = rowData.name;
          this.properties.sequenceDefinitionId = rowData.id;
          break;
        case 'labelTemplateModal':
          this.properties.labelTemplateId = rowData.id;
          this.properties.labelTemplateName = rowData.fileName;
          break;
        case 'printersModal':
          this.properties.printerId = rowData.id;
          this.properties.printerName = rowData.name;
          break;
        default:
          break;
      }
    },
    /**
     * 打开序列号规则选择模态框
     */
    openSequenceDefinitionModal() {
      this.modalName = 'sequenceDefineModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?subTypeList=raw_material_packaging,finished_product_packaging&type=material',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: `/api/mes-admin/labeltemplate/page?subTypeList=raw_material_packaging,finished_product_packaging&type=material&status=1`,
        isPage: true,
        rowSelectionType: 'single',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '模版名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '模版代码',
            prop: 'code',
            search: true
          },
          {
            label: '客户/供应商',
            prop: 'clientName'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
.receiving-container {
  height: 82vh;
  margin: 0 12px;
}
::v-deep .avue-crud__menu {
  display: none;
}
</style>
